package com.showsu.editor.manage;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.showsu.editor.entity.bo.XhsAwemeBusinessV2;
import com.showsu.editor.entity.bo.XhsAwemeLinkBaseInfo;
import com.showsu.editor.entity.doo.UserPrivilege;
import com.showsu.editor.entity.dto.*;
import com.showsu.editor.entity.platform.xhs.AwemeDetailPlatformDataResult;
import com.showsu.editor.entity.platform.xhs.AwemeDetailPlatformResult;
import com.showsu.editor.entity.platform.xhs.XhsAwemeCommentInfo;
import com.showsu.editor.entity.platform.xhs.XhsAwemeDetailResult;
import com.showsu.editor.entity.po.TblUser;
import com.showsu.editor.entity.po.TblUserPrivilege;
import com.showsu.editor.entity.tikhub.TikhubXhsAwemeCommentListResp;
import com.showsu.editor.entity.vo.AwemeCommentLiveImgVO;
import com.showsu.editor.entity.vo.XhsAwemeDetail;
import com.showsu.editor.entity.vo.XhsAwemeV2Resp;
import com.showsu.editor.entity.vo.response.*;
import com.showsu.editor.enums.*;
import com.showsu.editor.service.IUserPrivilegeService;
import com.showsu.editor.service.IUserService;
import com.showsu.editor.service.IXhsAwemeDetailRecordService;
import com.showsu.editor.service.IXhsDewaterRecordService;
import com.showsu.editor.utils.*;
import com.showsu.editor.utils.aliyun.OssUtil;
import com.showsu.editor.utils.remote.SelfAPIUtil;
import com.showsu.editor.utils.remote.ShuXiuUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 1:43 下午 2024/9/14
 * @Modified By:
 */
@Component
@Slf4j
public class XhsBusinessManager {

    @Autowired
    private RemoteIntegrationUtil remoteIntegrationUtil;

    @Autowired
    private SelfAPIUtil selfAPIUtil;

    @Autowired
    private OssUtil ossUtil;

    @Autowired
    private IUserPrivilegeService userPrivilegeService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IXhsDewaterRecordService xhsDewaterRecordService;

    @Autowired
    private IXhsAwemeDetailRecordService xhsAwemeDetailRecordService;

    @Autowired
    private ShuXiuUtils shuXiuUtils;


    /**
     * 获取作品详情
     * @return
     */
    public XhsAwemeDetail getXhsAwemeDetail(String awemeId, String xSecToken) {
        XhsAwemeDetail result = null;
        XhsPortalParseDTO xhsPortalParseDTO = new XhsPortalParseDTO();
        xhsPortalParseDTO.setAwemeId(awemeId);
        //把xSecToken加上，返回给前端，用于页面组装url跳转到xhs笔记pc端页面
        xhsPortalParseDTO.setXSecToken(xSecToken);
        ShuXiuCommonDTO res = shuXiuUtils.getXhsAwemeDetail(xhsPortalParseDTO);
        if (res == null) {
            return result;
        }
        if (res.getCode().equals(String.valueOf(ResultCode.SUCCESS.getCode()))) {
            if (StringUtils.isNotBlank(res.getData())) {
                try {
                    result = JSON.parseObject(res.getData(), XhsAwemeDetail.class);
                    result.setXSecToken(xSecToken);
                    if (result != null && StringUtils.isBlank(result.getTitle())
                            && (StringUtils.isNotBlank(result.getNote().getTitle()) || StringUtils.isNotBlank(result.getNote().getDesc()))) {
                        result.setTitle(StringUtils.isNotBlank(result.getNote().getTitle()) ? result.getNote().getTitle() : result.getNote().getDesc());
                    } else if (result != null && StringUtils.isNotBlank(result.getTitle()) && result.getTitle().indexOf("该笔记暂未设置标题") > -1
                            && (StringUtils.isNotBlank(result.getNote().getTitle()) || StringUtils.isNotBlank(result.getNote().getDesc()))) {
                        result.setTitle(StringUtils.isNotBlank(result.getNote().getTitle()) ? result.getNote().getTitle() : result.getNote().getDesc());
                    }
                } catch (Exception e) {
                    log.error("XhsBusinessManager.getXhsAwemeDetail", e);
                }
            }
        }
        return result;
    }

    /**
     * 获取用户笔记限流结果
     * @return
     */
    public XhsAwemeLimitedDTO getXhsAwemeLimited(String xhsUserId, String awemeId) {
        XhsAwemeLimitedDTO result = null;
        CheckAwemeIncludedDTO req = new CheckAwemeIncludedDTO();
        req.setUserid(xhsUserId);
        req.setAwemeId(awemeId);
        ShuXiuCommonDTO res = shuXiuUtils.getXhsAwemeLimited(req);
        if (res == null) {
            return result;
        }
        if (res.getCode().equals(String.valueOf(ResultCode.SUCCESS.getCode()))) {
            if (StringUtils.isNotBlank(res.getData())) {
                try {
                    result = JSON.parseObject(res.getData(), XhsAwemeLimitedDTO.class);
                } catch (Exception e) {
                    log.error("XhsBusinessManager.getXhsAwemeLimited", e);
                }
            }
        }
        return result;
    }

    /**
     * 小红书-笔记收录查询-搜素结果
     *
     * @return
     */
    public XhsAwemeBusinessV2 getAwemeIncludedSearchResult(XhsAwemeDetail awemeInfo, String keyword) {
        XhsAwemeBusinessV2 result = null;
        CheckAwemeIncludedDTO req = new CheckAwemeIncludedDTO();
        req.setAwemeId(awemeInfo.getAwemeId());
        req.setKeyword(keyword);
        req.setPublishTime(awemeInfo.getPublishTime());
        AwemeDetailPlatformDataResult.Note note = awemeInfo.getNote();
        if (note != null) {
            req.setTitle(note.getTitle());
            req.setDesc(note.getDesc());
            req.setText(note.getText());
            req.setType(note.getType());
        }
        AwemeDetailPlatformDataResult.User user = awemeInfo.getUser();
        if (user != null && user.getRed_id() != null) {
            req.setRedId(user.getRed_id());
        }
        ShuXiuCommonDTO res = shuXiuUtils.getAwemeIncludedSearchResult(req);
        if (res == null) {
            log.error("XhsBusinessManager.getAwemeIncludedSearchResult result:");
            return result;
        }
        if (res.getCode().equals(String.valueOf(ResultCode.SUCCESS.getCode()))) {
            if (StringUtils.isNotBlank(res.getData())) {
                try {
                    result = JSON.parseObject(res.getData(), XhsAwemeBusinessV2.class);
                } catch (Exception e) {
                    log.error("XhsBusinessManager.getAwemeIncludedSearchResult,e:{}", e);
                }
            }
        } else {
            log.error("XhsBusinessManager.getAwemeIncludedSearchResult result:{}", res);
        }
        return result;
    }

    /**
     * 获取作品详情
     * @return
     */
    public XhsAwemeIncludedDTO getAwemeIncluded(XhsAwemeIsLimitedEnum xhsAwemeIsLimitedEnum, XhsAwemeBusinessV2 includedSearchResult){
        XhsAwemeIncludedDTO result=null;
        CheckAwemeIncludedDTO req=new CheckAwemeIncludedDTO();
        req.setIsLimitedCode(xhsAwemeIsLimitedEnum.getCode());
        req.setIncludedSearchResult(includedSearchResult);
        ShuXiuCommonDTO res=shuXiuUtils.getAwemeIncluded(req);
        if(res==null){
            return result;
        }
        if(res.getCode().equals(String.valueOf(ResultCode.SUCCESS.getCode()))){
            if(StringUtils.isNotBlank(res.getData())){
                try {
                    result= JSON.parseObject(res.getData(), XhsAwemeIncludedDTO.class);
                }catch (Exception e){
                    log.error("XhsBusinessManager.getAwemeIncluded",e);
                }
            }
        }
        return  result;
    }

    public XhsAwemeIsIncludedEnum getAwemeIsIncluded(XhsAwemeIsLimitedEnum limited,XhsAwemeIsIncludedEnum included) {
        XhsAwemeIsIncludedEnum resp=included;
        if(XhsAwemeIsIncludedEnum.Included.equals(included)
                ||XhsAwemeIsLimitedEnum.Normal.equals(limited)
        ){
            resp=XhsAwemeIsIncludedEnum.Included;
        }else if(XhsAwemeIsLimitedEnum.Limited.equals(limited)){
            resp=XhsAwemeIsIncludedEnum.NotIncluded;
        }else if(XhsAwemeIsIncludedEnum.Fail.equals(included)
                &&XhsAwemeIsLimitedEnum.Fail.equals(limited)
        ){
            resp=XhsAwemeIsIncludedEnum.Fail;
        }else if(included==null){
            resp=XhsAwemeIsIncludedEnum.Fail;
        }
        return resp;
    }

    /**
     * 小红书-笔记收录查询-收录结果
     * @param xhsAwemeIsLimitedEnum
     * @param xhsAwemeBusiness
     * @return
     */
    public XhsAwemeIncludedDTO checkAwemeIncludedResult(XhsAwemeIsLimitedEnum xhsAwemeIsLimitedEnum, XhsAwemeBusinessV2 xhsAwemeBusiness){
        XhsAwemeIncludedDTO resp=new XhsAwemeIncludedDTO();
        switch (xhsAwemeBusiness.getIncluded()){
            case Included:
                resp.setSearchCriteria(xhsAwemeBusiness.getSearchCriteria());
                break;
        }
        XhsAwemeIsIncludedEnum isIncludedEnum=this.getAwemeIsIncluded(xhsAwemeIsLimitedEnum,xhsAwemeBusiness.getIncluded());
        switch (isIncludedEnum){
            case Included:
                resp.setIsIncluded("已收录");
                break;
            case NotIncluded:
                resp.setIsIncluded("未收录");
                break;
            case Fail:
                resp.setIsIncluded(Constant.analyzeHit7);
                break;
            default:
                resp.setIsIncluded(Constant.analyzeHit13);
                break;
        }
        return resp;
    }


        public XhsAwemeV2Resp formatAwemeBaseInfo(XhsAwemeDetail awemeInfo) {
        XhsAwemeV2Resp resp = new XhsAwemeV2Resp();
        resp.setAwemeId(awemeInfo.getAwemeId());
        resp.setCover(awemeInfo.getCover());
        if(StringUtils.isNotBlank(resp.getCover())){
            resp.setCover(resp.getCover().replace("/format/heif","/format/jpg"));
        }
        resp.setTitle(awemeInfo.getTitle());
        resp.setNickname(awemeInfo.getNickname());
        if(awemeInfo.getUser()!=null){
            resp.setAvatar(awemeInfo.getUser().getImage());
            if(StringUtils.isNotBlank(resp.getAvatar())){
                resp.setAvatar(resp.getAvatar().replace("/format/heif","/format/jpg"));
            }
        }
        resp.setPublishTime(awemeInfo.getPublishTime());
        resp.setLastUpdateTime(awemeInfo.getLastUpdateTime());
        resp.setQueryTime(awemeInfo.getQueryTime());
        resp.setXSecToken(awemeInfo.getXSecToken());
        if(awemeInfo.getNote()!=null){
            resp.setLiked(awemeInfo.getNote().getLiked_count());
            resp.setCollected(awemeInfo.getNote().getCollected_count());
            resp.setComments(awemeInfo.getNote().getComments_count());
        }
        return resp;
    }

    public HistroyStatusEnum getCheckAwemeIncludedStatus(Integer isLimited, Integer isIncluded, Date finishTime, Date lastUpdateTime) {
        if (isLimited != null && isIncluded != null) {
            if (XhsAwemeIsLimitedEnum.Fail.getCode() == isLimited
                    && XhsAwemeIsIncludedEnum.Fail.getCode() == isIncluded
            ) {
                return HistroyStatusEnum.Error;
            } else {
                return HistroyStatusEnum.Complete;
            }
        } else {
            //如果5分钟都没刷新，说明任务异常
            if (finishTime == null && System.currentTimeMillis() - lastUpdateTime.getTime() > 300000) {
                return HistroyStatusEnum.Error;
            } else {
                if (isLimited == null && isIncluded == null) {
                    return HistroyStatusEnum.Not_Started;
                } else {
                    return HistroyStatusEnum.Running;
                }
            }
        }
    }

    /**
     * 检查用户是否被限制了使用业务的权限
     * @param userId
     * @return true：被限制了，false：无限制，可以用
     */
    public boolean checkLimit(Long userId, DewaterTypeEnum dewaterTypeEnum) {
        if(dewaterTypeEnum == null){
            return true;
        }
        TblUser tblUser = userService.getById(userId);
        if (tblUser == null) {
            return true;
        }
        UserPrivilege userPrivilege = null;
        if (tblUser.getVipLevelCode() != null && ! tblUser.getVipLevelCode().equals(VipLevelEnum.FREE.getCode())) {
            userPrivilege = userPrivilegeService.queryByUserIdAndPrivilegeName(userId, dewaterTypeEnum.getUp().getCode());
        }
        if (null == userPrivilege) {
            //说明这是免费用户，免费用户1天有1次机会，总共5次
            int countTotal = xhsDewaterRecordService.queryCountOfUser(userId,dewaterTypeEnum.getType());
            if (countTotal >= 5) {
                return true;
            }
            int countToday = xhsDewaterRecordService.queryCountOfUserWithDate(userId,dewaterTypeEnum.getType(), DateUtil.getStartDateToday(), DateUtil.getEndDateToday());
            if (countToday < VipLevelEnum.FREE.getXhsLive().intValue()) {
                return false;
            }
        } else if (userPrivilege.getRemainTimes() > 0) {
            return false;
        }
        return true;
    }

    /**
     * 检查用户是否被限制了笔记收录查询笔记详情接口查询的权限
     * @param userId
     * @return -1,0：被限制了，>0：剩余次数
     */
    public Integer checkAwemeIncludedBaseInfoLimit(Long userId) {
        TblUser tblUser = userService.getById(userId);
        if (tblUser == null) {
            return -1;
        }
        Date today = new Date();
        Date todayBegin = cn.hutool.core.date.DateUtil.beginOfDay(today);
        Date todayEnd = cn.hutool.core.date.DateUtil.endOfDay(today);
        Integer todayUsedCnt = xhsAwemeDetailRecordService.queryCount(userId, todayBegin, todayEnd);
        //每天超过300次就被限制,这里返回剩余次数
        if (todayUsedCnt < 300) {
            return 300-todayUsedCnt;
        }
        return 0;
    }

    /**
     * 检查用户是否拥有使用业务的权限与次数
     * @param userId
     * @return
     */
    public Integer getUserPrivilegeTimes(Long userId,UserPrivilegeEnum privilegeEnum) {
        if(privilegeEnum==null){
            return -1;
        }
        UserPrivilege userPrivilege = userPrivilegeService.queryByUserIdAndPrivilegeName(userId, privilegeEnum.getCode());
        if (null == userPrivilege) {
            //说明这是免费用户
            return null;
        } else {
            return userPrivilege.getRemainTimes();
        }
    }

    /**
     * 扣减用户的权益次数
     * @param userId
     * @param times
     * @return
     */
    public boolean reduceTime(Long userId, UserPrivilegeEnum privilegeEnum, long times) {
        if(privilegeEnum==null){
            return false;
        }
        UserPrivilege userPrivilege = userPrivilegeService.queryByUserIdAndPrivilegeName(userId, privilegeEnum.getCode());
        if (userPrivilege == null) {
            return false;
        }
        if(userPrivilege.getRemainTimes() <= 0){
            return false;
        }
        UpdateWrapper<TblUserPrivilege> updateWrapper = new UpdateWrapper();
        updateWrapper.setSql("remain_times = remain_times - " + times);
        updateWrapper.eq("id", userPrivilege.getId());
        userPrivilegeService.update(updateWrapper);
        return true;
    }

    /**
     * 获取 含有live实况图的笔记中的素材
     * @param source
     * @return
     */
    public LiveImgVO handleLiveImageMovVersion(String source){
        XhsAwemeLinkBaseInfo xhsAwemeLinkBaseInfo = getAwemeIdFromSource(source);
        if (StringUtils.isBlank(xhsAwemeLinkBaseInfo.getAwemeId())) {
            return null;
        }
        LiveImgVO result = new LiveImgVO();
        XhsAwemeDetailResult xhsAwemeDetailResult = remoteIntegrationUtil.getXhsAwemeDetailForLive(xhsAwemeLinkBaseInfo.getAwemeId(), xhsAwemeLinkBaseInfo.getXSecToken());
        //若没有查询到结果，则用selfApi的接口再查一次，作为业务兜底逻辑。因为目前xhs查动图的接口不大稳定。
//        List<LiveImgVO.LiveImageInfo> liveImageList = getLiveImageListFromAwemeDetailPlatformResultMovVersion(xhsAwemeDetailResult);
//        if (liveImageList.size() == 0) {
//            xhsAwemeDetailResult = selfAPIUtil.getXhsAwemeDetail(xhsAwemeLinkBaseInfo.getAwemeId(), Constant.INTERFACEID_SELFAPI_API_XHS_NOTE_DETAIL_V1);
//        }
        if (xhsAwemeDetailResult == null) {
            return null;
        }
        if (xhsAwemeDetailResult.getData() == null
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData())
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData().get(0).getNote_list())) {
            return result;
        }
        result.setRequestSuccess(true);
        AwemeDetailPlatformResult.AwemeDetail.Note note = xhsAwemeDetailResult.getData().getData().get(0).getNote_list().get(0);
        //获取文案
        if (note.getShare_info() != null && StringUtils.isNotBlank(note.getShare_info().getTitle())) {
            StringBuilder text = new StringBuilder(note.getShare_info().getTitle()).
                    append(StringUtils.isBlank(note.getShare_info().getContent()) ? "" : " " + note.getShare_info().getContent());
            result.setText(text.toString());
        }
        //获取Live实况图链接
        if (CollectionUtils.isEmpty(note.getImages_list())) {
            return result;
        }
//        if (liveImageList.size() == 0) {
        List<LiveImgVO.LiveImageInfo> liveImageList = getLiveImageListFromAwemeDetailPlatformResultMovVersion(xhsAwemeDetailResult);
//        }
        result.setLiveImages(liveImageList);

        return result;
    }

    /**
     * 从XhsAwemeDetailResult对象中获取live图片
     * @param xhsAwemeDetailResult
     * @return
     */
    private List<LiveImgVO.LiveImageInfo> getLiveImageListFromAwemeDetailPlatformResultMovVersion(XhsAwemeDetailResult xhsAwemeDetailResult) {
        List<LiveImgVO.LiveImageInfo> liveImageList = new ArrayList<>();
        if (xhsAwemeDetailResult == null
                || xhsAwemeDetailResult.getData() == null
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData())
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData().get(0).getNote_list())
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData().get(0).getNote_list().get(0).getImages_list())) {
            return liveImageList;
        }
        List<AwemeDetailPlatformResult.AwemeDetail.Note.Image> imageList = xhsAwemeDetailResult.getData().getData().get(0).getNote_list().get(0).getImages_list();
        for (AwemeDetailPlatformResult.AwemeDetail.Note.Image image : imageList) {
            if (image.getLive_photo() == null
                    || image.getLive_photo().getMedia() == null
                    || image.getLive_photo().getMedia().getStream() == null
            ) {
                if(image.getStream()==null){
                    continue;
                }else{
                    AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto livePhoto=new AwemeDetailPlatformResult().new AwemeDetail(). new Note(). new Image().new  LivePhoto();
                    AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media media=new AwemeDetailPlatformResult().new AwemeDetail(). new Note(). new Image().new  LivePhoto().new Media();
                    media.setStream(image.getStream());
                    livePhoto.setMedia(media);
                    image.setLive_photo(livePhoto);
                }
            }
            String masterUrl="";
            if (! CollectionUtils.isEmpty(image.getLive_photo().getMedia().getStream().getH265())
                    && image.getLive_photo().getMedia().getStream().getH265().get(0) != null
            ) {
                if(StringUtils.isNotBlank(image.getLive_photo().getMedia().getStream().getH265().get(0).getMaster_url())){
                    masterUrl=image.getLive_photo().getMedia().getStream().getH265().get(0).getMaster_url();
                }else if(StringUtils.isNotBlank(image.getLive_photo().getMedia().getStream().getH265().get(0).getMasterUrl())) {
                    masterUrl=image.getLive_photo().getMedia().getStream().getH265().get(0).getMasterUrl();
                }

            }
            if (! CollectionUtils.isEmpty(image.getLive_photo().getMedia().getStream().getH264())
                    && image.getLive_photo().getMedia().getStream().getH264().get(0) != null
            ) {
                if(StringUtils.isNotBlank(image.getLive_photo().getMedia().getStream().getH264().get(0).getMaster_url())){
                    masterUrl=image.getLive_photo().getMedia().getStream().getH264().get(0).getMaster_url();
                }else if(StringUtils.isNotBlank(image.getLive_photo().getMedia().getStream().getH264().get(0).getMasterUrl())){
                    masterUrl=image.getLive_photo().getMedia().getStream().getH264().get(0).getMasterUrl();
                }
            }
            if(StringUtils.isNotBlank(masterUrl)){
                LiveImgVO.LiveImageInfo liveImageInfo=new LiveImgVO().new LiveImageInfo();
                String suffix= FileUtil.getSuffix(StrUtil.subBefore(masterUrl,"?",true));
                suffix=StringUtils.isBlank(suffix)?"mov":suffix;
                //2. live去水印流量优化：接口获取展示封面图；文件优先客户端下载
                //mp4 文件较小 为了避免无法下载 所以进行上次到oss
                if("mp4".equals(suffix)){
                    //xhs的资源域名比较多，暂时不能做到全覆盖，因此不使用小程序管理后台配置的downloadFile合法域名。这里上传到oss，再提供给用户下载。
                    String imageUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(masterUrl,
                            Constant.xhsAwemeLiveHandlePrefix + IdUtil.simpleUUID() + "."+suffix);
                    liveImageInfo.setUrl(imageUrl);
                }else{
                        String imgSufFix=FileUtil.getSuffix(image.getUrl());
                        imgSufFix=StringUtils.isBlank(imgSufFix)?"jpg":imgSufFix;
                        if(StringUtils.contains(image.getUrl(),"/format/reif")){
                            image.setUrl(StringUtils.replace(image.getUrl(),"/format/reif","/format/"+imgSufFix));
                        }
                        String cover = ossUtil.uploadHandleWaterDirFile2AliyunOss(image.getUrl(),
                                Constant.xhsAwemeLiveHandlePrefix + IdUtil.simpleUUID() + "."+imgSufFix);
                        liveImageInfo.setCover(cover);
                        liveImageInfo.setUrl(masterUrl);
                    if(StringUtils.endsWithIgnoreCase("mov",suffix)){
                        liveImageInfo.setHaveAudioTrack(true);
                    }else{
                        liveImageInfo.setHaveAudioTrack(false);
                    }
                }

                liveImageList.add(liveImageInfo);
            }
        }
        return liveImageList;
    }

    /**
     * xhs live去水印，也支持获取普通的图片
     * @param source
     * @return
     */
    public XhsLiveVO handleLiveImageFromAwemeDetail(String source) {
        XhsAwemeLinkBaseInfo xhsAwemeLinkBaseInfo = getAwemeIdFromSource(source);
        if (StringUtils.isBlank(xhsAwemeLinkBaseInfo.getAwemeId())) {
            return null;
        }
        XhsLiveVO result = new XhsLiveVO();
        XhsAwemeDetailResult xhsAwemeDetailResult = remoteIntegrationUtil.getXhsAwemeDetailForLive(xhsAwemeLinkBaseInfo.getAwemeId(), xhsAwemeLinkBaseInfo.getXSecToken());
        //若没有查询到结果，则用selfApi的接口再查一次，作为业务兜底逻辑。因为目前xhs查动图的接口不大稳定。
        List<String> imageList = new ArrayList<>();
        List<String> liveImageList = new ArrayList<>();
        getLiveImageListFromAwemeDetailPlatformResult(xhsAwemeDetailResult, imageList, liveImageList);
        if (imageList.size() == 0 && liveImageList.size() == 0) {
            xhsAwemeDetailResult = selfAPIUtil.getXhsAwemeDetail(xhsAwemeLinkBaseInfo.getAwemeId(), Constant.INTERFACEID_SELFAPI_API_XHS_NOTE_DETAIL_V1);
        }
        if (xhsAwemeDetailResult == null) {
            return null;
        }
        if (xhsAwemeDetailResult.getData() == null
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData())
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData().get(0).getNote_list())) {
            return result;
        }
        result.setRequestSuccess(true);
        AwemeDetailPlatformResult.AwemeDetail.Note note = xhsAwemeDetailResult.getData().getData().get(0).getNote_list().get(0);
        result.setTitle(note.getTitle());
        //获取文案
        if (note.getShare_info() != null && StringUtils.isNotBlank(note.getShare_info().getTitle())) {
            StringBuilder text = new StringBuilder(note.getShare_info().getTitle()).
                    append(StringUtils.isBlank(note.getShare_info().getContent()) ? "" : " " + note.getShare_info().getContent());
            result.setText(text.toString());
        }
        if (liveImageList.size() == 0) {
            getLiveImageListFromAwemeDetailPlatformResult(xhsAwemeDetailResult, imageList, liveImageList);
        }
        result.setImageList(imageList);
        result.setVideoList(liveImageList);

        return result;
    }

    /**
     * 通过xhs作品链接获取作品id、xsec_token等信息
     * @param source
     * @return
     */
    /**
     * 通过xhs作品链接获取作品id、xsec_token等信息
     * @param source
     * @return
     */
    public XhsAwemeLinkBaseInfo getAwemeIdFromSource(String source) {
        XhsAwemeLinkBaseInfo result = new XhsAwemeLinkBaseInfo();
        if (StringUtils.isBlank(source)) {
            return result;
        }
        String awemeId = null;
        String xSecToken = null;
        String xSecTokenStartCut = "xsec_token=";
        try {
            if (source.contains(Constant.xhsLinkPrefix0)) {
                String xhsLongLink = getLongUrlFromSource(source);

                String awemeIdStartCut = "/item/";
                String awemeIdFromSub = StringUtil.subStringFromHttpUrl(xhsLongLink, awemeIdStartCut, "?");
                awemeId = awemeIdFromSub.replace(awemeIdStartCut, "");

                if (xhsLongLink.indexOf(xSecTokenStartCut) > -1) {
                    String xSecTokenFromSub = xhsLongLink.substring(xhsLongLink.indexOf(xSecTokenStartCut));
                    xSecToken = xSecTokenFromSub.indexOf("&") > -1 ?
                            xSecTokenFromSub.substring(0, xSecTokenFromSub.indexOf("&")).replace(xSecTokenStartCut, "")
                            : xSecTokenFromSub.replace(xSecTokenStartCut, "");
                }
            } else if (source.contains(Constant.xhsLinkPrefix1) && source.contains("/explore/")) {
                String startCut = "/explore/";
                String awemeIdFromSub = StringUtil.subStringFromHttpUrl(source, startCut, "?");
                awemeId = awemeIdFromSub.replace(startCut, "");

                if (source.indexOf(xSecTokenStartCut) > -1) {
                    String xSecTokenFromSub = source.substring(source.indexOf(xSecTokenStartCut));
                    xSecToken = xSecTokenFromSub.indexOf("&") > -1 ?
                            xSecTokenFromSub.substring(0, xSecTokenFromSub.indexOf("&")).replace(xSecTokenStartCut, "")
                            : xSecTokenFromSub.replace(xSecTokenStartCut, "");
                }
            } else if (source.contains(Constant.xhsLinkPrefix1) && source.contains("/discovery/item/")) {
                String startCut = "/discovery/item/";
                String awemeIdFromSub = StringUtil.subStringFromHttpUrl(source, startCut, "?");
                awemeId = awemeIdFromSub.replace(startCut, "");

                if (source.indexOf(xSecTokenStartCut) > -1) {
                    String xSecTokenFromSub = source.substring(source.indexOf(xSecTokenStartCut));
                    xSecToken = xSecTokenFromSub.indexOf("&") > -1 ?
                            xSecTokenFromSub.substring(0, xSecTokenFromSub.indexOf("&")).replace(xSecTokenStartCut, "")
                            : xSecTokenFromSub.replace(xSecTokenStartCut, "");
                }
            } else if (source.contains(Constant.xhsLinkPrefix2)) {
                String xhsLongLink = getLongUrlFromSource(source);
                String awemeIdStartCut = "/explore/";
                if (xhsLongLink.indexOf(awemeIdStartCut) == -1) {
                    awemeIdStartCut = "/discovery/item/";
                }
                String awemeIdFromSub = StringUtil.subStringFromHttpUrl(xhsLongLink, awemeIdStartCut, "?");
                awemeId = awemeIdFromSub.replace(awemeIdStartCut, "");

                if (xhsLongLink.indexOf(xSecTokenStartCut) > -1) {
                    String xSecTokenFromSub = xhsLongLink.substring(xhsLongLink.indexOf(xSecTokenStartCut));
                    xSecToken = xSecTokenFromSub.indexOf("&") > -1 ?
                            xSecTokenFromSub.substring(0, xSecTokenFromSub.indexOf("&")).replace(xSecTokenStartCut, "")
                            : xSecTokenFromSub.replace(xSecTokenStartCut, "");
                }
            }
        } catch (Exception e) {
            log.error("PortalParseServiceImpl.getAwemeIdFromSource(String) error,source:{}", source, e);
        }
        result.setAwemeId(awemeId);
        result.setXSecToken(xSecToken);
        return result;
    }

    /**
     * 通过xhs作品链接获取作品id
     * @param source
     * @return
     */
    private String getLongUrlFromSource(String source) {
        if (StringUtils.isBlank(source)) {
            return null;
        }
        //  获取小红书的链接
        String xhslink = StringUtil.resolveXhsHttpUrl(source);
        if (StringUtils.isBlank(xhslink)) {
            return null;
        }
        String longUrl=null;
        try {
            if (Constant.checkSourceContainsXhsLinkPrefix(source)) {
                longUrl = HttpUtil.get(xhslink);
            }else{
                longUrl=xhslink;
            }
            longUrl=HttpClientUtil.extractUrl(longUrl);
        } catch (Exception e) {
            log.error("PortalParseServiceImpl.getLongUrlFromSource(String) error,source:{}", source, e);
        }
        return longUrl;
    }




    /**
     * 通过移动端链接获取笔记是否可以正常展示
     * @param awemeId
     * @return
     */
    public Boolean getAwemeNormalDisplay(String awemeId) {
        return this.getAwemeNormalDisplay(awemeId,null);
    }

    /**
     * 通过移动端链接获取笔记是否可以正常展示
     * @param awemeId
     * @param xSecToken
     * @return
     */
    public Boolean getAwemeNormalDisplay(String awemeId, String xSecToken){
        boolean awemeNormalDisplay = true;
        Map<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1");
        StringBuilder url=new StringBuilder("https://www.xiaohongshu.com/discovery/item/")
                .append(awemeId).append("?app_platform=ios&app_version=8.8.1");
        if(StringUtils.isNotBlank(xSecToken)){
            url.append("&xsec_token=").append(xSecToken);
        }
        String response = HttpClientUtil.get(url.toString(), null, headers, null, null);
        if (StringUtils.isNotBlank(response) && response.contains(Constant.analyzeHit18)) {
            awemeNormalDisplay = false;
        }
        return awemeNormalDisplay;
    }

    /**
     * 从XhsAwemeDetailResult对象中获取live图片、普通图片
     * @param xhsAwemeDetailResult
     * @return
     */
    private void getLiveImageListFromAwemeDetailPlatformResult(XhsAwemeDetailResult xhsAwemeDetailResult, List<String> imageList, List<String> liveImageList) {
        if (xhsAwemeDetailResult == null
                || xhsAwemeDetailResult.getData() == null
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData())
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData().get(0).getNote_list())
                || CollectionUtils.isEmpty(xhsAwemeDetailResult.getData().getData().get(0).getNote_list().get(0).getImages_list())) {
            return;
        }
        List<AwemeDetailPlatformResult.AwemeDetail.Note.Image> platformResultImageList = xhsAwemeDetailResult.getData().getData().get(0).getNote_list().get(0).getImages_list();
        for (AwemeDetailPlatformResult.AwemeDetail.Note.Image image : platformResultImageList) {
            if (image.getLive_photo() == null
                    || image.getLive_photo().getMedia() == null
                    || image.getLive_photo().getMedia().getStream() == null
            ) {
                if(image.getStream() == null) {
                    //获取普通图片
                    //xhs的资源域名比较多，暂时不能做到全覆盖，因此不使用小程序管理后台配置的downloadFile合法域名。这里上传到oss，再提供给用户下载。
                    String imageUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(image.getUrl(), UUID.randomUUID().toString().replaceAll("-","") + ".png");
                    imageList.add(imageUrl);
                    continue;
                } else {
                    AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto livePhoto = new AwemeDetailPlatformResult().new AwemeDetail(). new Note(). new Image().new  LivePhoto();
                    AwemeDetailPlatformResult.AwemeDetail.Note.Image.LivePhoto.Media media = new AwemeDetailPlatformResult().new AwemeDetail(). new Note(). new Image().new  LivePhoto().new Media();
                    media.setStream(image.getStream());
                    livePhoto.setMedia(media);
                    image.setLive_photo(livePhoto);
                }
            }
            String masterUrl = "";
            if (! CollectionUtils.isEmpty(image.getLive_photo().getMedia().getStream().getH265())
                    && image.getLive_photo().getMedia().getStream().getH265().get(0) != null
            ) {
                if(StringUtils.isNotBlank(image.getLive_photo().getMedia().getStream().getH265().get(0).getMaster_url())){
                    masterUrl = image.getLive_photo().getMedia().getStream().getH265().get(0).getMaster_url();
                }else if(StringUtils.isNotBlank(image.getLive_photo().getMedia().getStream().getH265().get(0).getMasterUrl())) {
                    masterUrl = image.getLive_photo().getMedia().getStream().getH265().get(0).getMasterUrl();
                }

            }
            if (! CollectionUtils.isEmpty(image.getLive_photo().getMedia().getStream().getH264())
                    && image.getLive_photo().getMedia().getStream().getH264().get(0) != null
            ) {
                if(StringUtils.isNotBlank(image.getLive_photo().getMedia().getStream().getH264().get(0).getMaster_url())){
                    masterUrl = image.getLive_photo().getMedia().getStream().getH264().get(0).getMaster_url();
                }else if(StringUtils.isNotBlank(image.getLive_photo().getMedia().getStream().getH264().get(0).getMasterUrl())){
                    masterUrl = image.getLive_photo().getMedia().getStream().getH264().get(0).getMasterUrl();
                }
            }
            if(StringUtils.isNotBlank(masterUrl)){
                //xhs的资源域名比较多，暂时不能做到全覆盖，因此不使用小程序管理后台配置的downloadFile合法域名。这里上传到oss，再提供给用户下载。
                String imageUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(masterUrl,
                        Constant.xhsAwemeLiveHandlePrefix + UUID.randomUUID().toString().replaceAll("-","") + ".mp4");
                liveImageList.add(imageUrl);
            }
        }
    }


    /**
     * 去水印原文
     * @param source
     * @param isOriginal 去水印后的作品（视频、图片）是否返回原地址。true-是，则会将接口返回的作品地址直接返回；false-否，则会将接口返回的作品上传到oss，将oss地址返回给上层业务。
     * @return
     */
    public VnilVO handleWater(String source, Boolean isOriginal){
        ShuXiuCommonDTO res=shuXiuUtils.dewater(source);
        return handleVnilVO(source,res,isOriginal);
    }

    /**
     *  获取 含有动图的笔记中的素材-
     * @param source
     * @return
     */
    public AnimImgVO handleAnimImage(String source, Boolean isOriginal){
        //动图需要返回原始链接 再处理，所以 isOriginal 入参 设置为 true
        VnilVO vnilVO = this.handleWater(source, true);

        AnimImgVO result = new AnimImgVO();
        result.setRequestSuccess(true);
        if (vnilVO == null ||! result.getRequestSuccess()) {
            result.setRequestSuccess(false);
            return result;
        }else{
            result.setPlatform(vnilVO.getPlatform());
            result.setUrl(vnilVO.getUrl());
            result.setText(vnilVO.getText());
            if (! CollectionUtils.isEmpty(vnilVO.getImages())) {
                List<String> imageList = new ArrayList<>();
                List<String> oImageList = new ArrayList<>();
                for(String oImgUrl : vnilVO.getImages()){
                    String imgUrl = oImgUrl;
                    imgUrl = StringUtil.subStringFromHttpUrl(imgUrl, "http", "?");
                    String imagesUrl = this.getAnimImage(imgUrl,isOriginal);
                    if(StringUtils.isNotBlank(imagesUrl)){
                        imageList.add(imagesUrl);
                        oImageList.add(oImgUrl);
                    }
                }
                if (! CollectionUtils.isEmpty(imageList)) {
                    result.setImages(imageList);
                    result.setOriginalImages(oImageList);
                }
            }
        }
        return result;
    }
    private String animGIFHeader="NETSCAPE2.0";
    private String animWebPHeader="ANIM";
    private String readLine(InputStream inputStream) throws IOException {
        StringBuilder lineBuilder = new StringBuilder();
        int len=0;
        while((len=inputStream.read()) != -1 ){
            char c=(char)((byte)len);
            lineBuilder.append(c);
            if (c == '\n' ||c == '\r') {
                break;
            }
        }
        if(lineBuilder.length()>0)
            return lineBuilder.toString();
        else
            return null;
    }
    private String getAnimImage(String imgUrl, Boolean isOriginal){
        String imagesUrl =null;
        try {
            URL url=new URL(imgUrl);
            URLConnection connection = url.openConnection();
            // 设置连接超时时间为5秒
            connection.setConnectTimeout(10000);
            // 设置读取超时时间为10秒
            connection.setReadTimeout(60000);
            //判断是否为动图
            // 文件头信息WebP静态图像的文件头信息通常以RIFF开头，后跟4个字节的文件大小和以WEBP开头的标识符。而WebP动态图像的文件头信息通常以RIFF开头，后跟4个字节的文件大小和以ANIM开头的标识符。
            int isAnimImg = 0;
            InputStream inputStream = null;
            try {
                inputStream = new BufferedInputStream(connection.getInputStream());
                String header=null;
                inputStream.mark(2048);
                // 使用readLine方法读取一行数据
                String line = this.readLine(inputStream);
                if(line==null){
                    return null;
                }
                int current = 0;
                int limit = 6;
                if(line.contains("GIF8")){
                    header=animGIFHeader;
                    isAnimImg=1;
                }else if(line.contains("WEBP")){
                    header=animWebPHeader;
                    isAnimImg=2;
                }
                while (header!=null&&line != null&&current<limit) {
                    // 处理文件头信息：
                    if(line.contains(header)){
                        if(header.equals(animGIFHeader)){
                            isAnimImg=3;
                        }else if(header.equals(animWebPHeader)){
                            isAnimImg=4;
                        }
                        if(isAnimImg>2){
                            String fileName=Constant.xhsAwemeAnimImgHandlePrefix + IdUtil.simpleUUID() ;
                            if(isAnimImg==3){
                                fileName+= ".gif";
                            }else if(isAnimImg==4){
                                fileName+= ".webp";
                            }
                            inputStream.reset();
                            if(isOriginal){
                                imagesUrl = fileName;
                            }else {
                                imagesUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(inputStream, fileName);
                            }

                        }
                        break;
                    }
                    //解决空行导致的无法读取文件头信息
                    if(line.length()>12){
                        current++;
                    }
                    // 继续读取下一行数据
                    line = this.readLine(inputStream);
                }
            }catch (IOException e) {
                log.error("XhsBusinessManager.getAnimImage error0", e);
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
            }
        } catch (IOException e) {
            log.error("XhsBusinessManager.getAnimImage error1", e);
        }
        return imagesUrl;
    }

    /**
     * 提取xhs作品评论区图片/文字
     * @param source
     * @return
     */
    public VnilVO handleCommentInfoWater(String source, Boolean isOriginal){
        ShuXiuCommonDTO res=shuXiuUtils.commentInfoDewater(source);
        return handleVnilVO(source,res,isOriginal);
    }

    private VnilVO handleVnilVO(String source,ShuXiuCommonDTO res, Boolean isOriginal){
        VnilVO  result=new VnilVO();
        if(res==null){
            result.setRequestSuccess(false);
            return result;
        }
        result.setRequestSuccess(true);
        if(res.getCode().equals(String.valueOf(ResultCode.SUCCESS.getCode()))){
            if(StringUtils.isNotBlank(res.getData())){
                try {
                    result= JSON.parseObject(res.getData(),VnilVO.class);
                    if(StringUtils.isBlank(result.getUrl())){
                        result.setUrl(StringUtil.resolveXhsHttpUrl(source));
                    }
                }catch (Exception e){
                    log.error("XhsBusinessManager.handleWater",e);
                }
            }
            if(result==null){
                result=new VnilVO();
            }
            result.setRequestSuccess(true);
            //接口返回的文件 传输协议为http,小程序只支持https，
            //研究发现 把文件url 的http  改为https 不影响访问
            //所以统一替换成https协议。

                //图集信息：包含所有图片地址校验
                if(!CollectionUtils.isEmpty(result.getImages())){
                    List<String> imageList=result.getImages();
                    for(int i =0;i<imageList.size();i++){
                        String imgesUrl =imageList.get(i);
                        if (StringUtils.isNotBlank(imgesUrl)){
                            if(imgesUrl.contains("/format/reif")){;
                                imgesUrl=imgesUrl.replace("/format/reif","/format/jpg");
                            }
                            if(isOriginal){
                                if(!imgesUrl.contains("https://")){
                                    imgesUrl=imgesUrl.replace("http://","https://");
                                }
                            }else{
                                imgesUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(imgesUrl, IdUtil.simpleUUID() + ".png");
                            }

                        }
                        imageList.set(i,imgesUrl);
                    }
                }
                //视频文件格式校验
                if(result.getVideo_info()!=null){
                    VnilVideo video=result.getVideo_info();
                    if (StringUtils.isNotBlank(video.getCover())){
                        if(video.getCover().contains("/format/reif")){;
                            video.setCover(video.getCover().replace("/format/reif","/format/jpg"));
                        }
                        if(isOriginal){
                            if(!video.getCover().contains("https://")){
                                video.setCover(video.getCover().replace("http://","https://"));
                            }
                        }else{
                            String imgesUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(video.getCover(), IdUtil.simpleUUID() + ".png");
                            video.setCover(imgesUrl);
                        }

                    }
                    if (StringUtils.isNotBlank(video.getUrl())){
                        if(isOriginal){
                            if(!video.getUrl().contains("https://")){
                                video.setUrl(video.getUrl().replace("http://","https://"));
                            }
                        }else{
                            String videoUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(video.getUrl(), IdUtil.simpleUUID() + ".mp4");
                            video.setUrl(videoUrl);
                        }
                    }
                }
                //封面图地址
                if (StringUtils.isNotBlank(result.getCover())){
                    if(result.getCover().contains("/format/reif")){;
                        result.setCover(result.getCover().replace("/format/reif","/format/jpg"));
                    }
                    if(isOriginal){
                        if(!result.getCover().contains("https://")){
                            result.setCover(result.getCover().replace("http://","https://"));
                        }
                    }else{
//                        String imgesUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(result.getCover(), IdUtil.simpleUUID() + ".png");
//                        result.setCover(imgesUrl);
                    }


                }
                //音频地址
                if (StringUtils.isNotBlank(result.getAudio())){
                    if(isOriginal){
                        if(!result.getAudio().contains("https://")){
                            result.setAudio(result.getAudio().replace("http://","https://"));
                        }
                    }else {
                        String audioUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(result.getAudio(), IdUtil.simpleUUID() + ".mp3");
                        result.setAudio(audioUrl);
                    }

                }
        }
        return result;
    }

    /**
     * 从xhs作品评论区中获取live图
     * @param source
     * @return
     */
    public AwemeCommentLiveImgVO handleLiveImageFromXhsAwemeCommentLis(String source) {
        XhsAwemeLinkBaseInfo xhsAwemeLinkBaseInfo = getAwemeIdFromSource(source);
        AwemeCommentLiveImgVO result = new AwemeCommentLiveImgVO();
        if (StringUtils.isBlank(xhsAwemeLinkBaseInfo.getAwemeId())) {
            return result;
        }
        result.setAwemeId(xhsAwemeLinkBaseInfo.getAwemeId());
        //第一页，分页参数传空
        TikhubXhsAwemeCommentListResp xhsAwemeCommentListResp0 = remoteIntegrationUtil.getXhsAwemeCommentListForLive(xhsAwemeLinkBaseInfo.getAwemeId(), "");
        if (xhsAwemeCommentListResp0 == null || xhsAwemeCommentListResp0.getData() == null
                || xhsAwemeCommentListResp0.getData().getData() == null) {
            result.setSuccess(false);
            return result;
        }
        if (CollectionUtils.isEmpty(xhsAwemeCommentListResp0.getData().getData().getComments())) {
            return result;
        }
        List<XhsAwemeCommentInfo> comments = new ArrayList<>();
        comments.addAll(xhsAwemeCommentListResp0.getData().getData().getComments());
        String cursor = xhsAwemeCommentListResp0.getData().getData().getCursor();
        //目前的接口通常返回10行/页或15行/页，暂时用这种硬编码的方式判断，等以后发现新的字段逻辑
        if (comments.size() >= 10) {
            //最多查30条评论的数据
            while (comments.size() < 30) {
                TikhubXhsAwemeCommentListResp xhsAwemeCommentListResp1 = remoteIntegrationUtil.getXhsAwemeCommentListForLive(xhsAwemeLinkBaseInfo.getAwemeId(), cursor);
                if (xhsAwemeCommentListResp0 == null || xhsAwemeCommentListResp0.getData() == null
                        || xhsAwemeCommentListResp0.getData().getData() == null || CollectionUtils.isEmpty(xhsAwemeCommentListResp0.getData().getData().getComments())) {
                    break;
                }
                comments.addAll(xhsAwemeCommentListResp1.getData().getData().getComments());
                cursor = xhsAwemeCommentListResp1.getData().getData().getCursor();
                if (xhsAwemeCommentListResp1.getData().getData().getComments().size() < 10) {
                    break;
                }
            }
        }
        if (comments.size() == 0) {
            return result;
        }
        List<String> textList = new ArrayList<>();
        List<AwemeCommentLiveImgVO.LiveImageInfo> liveImages = new ArrayList<>();
        result.setTextList(textList);
        result.setLiveImages(liveImages);
        //不同的接口返回的结果不同，有的接口翻到下一页，其中会包含上一页中的某个评论，因使用这个list做一下去重复
        List<String> handledCommentIdList = new ArrayList<>();
        for (XhsAwemeCommentInfo comment : comments) {
            if (StringUtils.isNotBlank(comment.getId())) {
                if (handledCommentIdList.contains(comment.getId())) {
                    continue;
                }
                handledCommentIdList.add(comment.getId());
            }
            if (StringUtils.isNotBlank(comment.getContent())) {
                textList.add(comment.getContent());
            }
            if (CollectionUtils.isEmpty(comment.getPictures())) {
                continue;
            }
            for (XhsAwemeCommentInfo.Image picture : comment.getPictures()) {
                if (picture.getVideoInfo() == null || picture.getVideoInfo().getStream() == null) {
                    continue;
                }
                if (! CollectionUtils.isEmpty(picture.getVideoInfo().getStream().getH264())) {
                    for (XhsAwemeCommentInfo.Image.VideoInfo.Stream.H264 h264 : picture.getVideoInfo().getStream().getH264()) {
                        if (StringUtils.isNotBlank(h264.getMaster_url())) {
                            handleAwemeCommentLiveImgVOLiveImageInfo(result, liveImages, picture, h264.getMaster_url());
                        } else if (StringUtils.isNotBlank(h264.getMasterUrl())) {
                            handleAwemeCommentLiveImgVOLiveImageInfo(result, liveImages, picture, h264.getMasterUrl());
                        }
                    }
                }
                if (! CollectionUtils.isEmpty(picture.getVideoInfo().getStream().getH265())) {
                    for (XhsAwemeCommentInfo.Image.VideoInfo.Stream.H264 h265 : picture.getVideoInfo().getStream().getH265()) {
                        if (StringUtils.isNotBlank(h265.getMaster_url())) {
                            handleAwemeCommentLiveImgVOLiveImageInfo(result, liveImages, picture, h265.getMaster_url());
                        } else if (StringUtils.isNotBlank(h265.getMasterUrl())) {
                            handleAwemeCommentLiveImgVOLiveImageInfo(result, liveImages, picture, h265.getMasterUrl());
                        }
                    }
                }
            }

        }
        return result;
    }

    /**
     * 处理评论区live图片数据
     * @param result 业务接口响应结果
     * @param liveImages 业务项目结果中的live图片列表
     * @param picture 抓取到的评论区图片对象
     * @param masterUrl 抓取到的评论区live图url
     */
    private void handleAwemeCommentLiveImgVOLiveImageInfo(AwemeCommentLiveImgVO result, List<AwemeCommentLiveImgVO.LiveImageInfo> liveImages,
                                                          XhsAwemeCommentInfo.Image picture, String masterUrl) {
        if (StringUtils.isBlank(picture.getUrl()) || StringUtils.isBlank(masterUrl)) {
            return;
        }
        String suffix = FileUtil.getSuffix(StrUtil.subBefore(masterUrl,"?",true));
        String videoUrl = null;
        if("mp4".equals(suffix)){
            //xhs的资源域名比较多，暂时不能做到全覆盖，因此不使用小程序管理后台配置的downloadFile合法域名。这里上传到oss，再提供给用户下载。
            videoUrl = ossUtil.uploadHandleWaterDirFile2AliyunOss(masterUrl,
                    Constant.xhsAwemeLiveHandlePrefix + IdUtil.simpleUUID() + "."+suffix);
        }
        if (StringUtils.isBlank(videoUrl)) {
            return;
        }
        String coverUtil = null;
        if (StringUtils.isNotBlank(picture.getUrl())) {
            String imgSufFix = FileUtil.getSuffix(picture.getUrl());
            imgSufFix = StringUtils.isBlank(imgSufFix) ? "jpg" : imgSufFix;
            coverUtil = ossUtil.uploadHandleWaterDirFile2AliyunOss(StringUtil.replaceReifString(picture.getUrl()),
                    Constant.xhsAwemeLiveHandlePrefix + IdUtil.simpleUUID() + "." + imgSufFix);
        }
        AwemeCommentLiveImgVO.LiveImageInfo liveImageInfo = result.new LiveImageInfo(coverUtil, videoUrl);
        liveImages.add(liveImageInfo);
    }

    /**
     * 获取xhs笔记推荐关键词
     * @param awemeId
     * @return
     */
    public List<XhsSearchHotKeywordDTO> getXhsAwemeRecommondKeywords(String awemeId) {
        return shuXiuUtils.getXhsAwemeRecommondKeywords(awemeId);
    }

}
